package com.mmx.baseservice.common.Interceptor;

import com.mmx.baseservice.admin.pojo.AdInfo;
import com.mmx.baseservice.admin.service.AdInfoService;
import com.mmx.baseservice.common.redis.utils.RedisUtil;
import com.mmx.baseservice.common.utils.CommUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class adminInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AdInfoService adInfoService;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // /tlManage/admin/adInfo/public/authority
        Integer adId = (Integer) request.getAttribute("adId");
        long l = Long.parseLong(String.valueOf(adId));
//        Long adId = 1L;
        if (CommUtil.checkNull(adId)) {
            AdInfo adInfo = adInfoService.getByIdForUpdate(adId);
            //默认全部权限，直接放行
            if (CommUtil.checkNull(adInfo) && adInfo.getIsDefault() == 0) {
                return true;
            }
            String requestURI = request.getRequestURI();
            //去掉前缀，如果没前缀取消这一步
            String substring = requestURI.substring(requestURI.indexOf("/", requestURI.indexOf("/") + 1));
            String authoURLlist = redisUtil.get("AUTHO" + adId).toString();
            if (authoURLlist.contains(substring)) {
                return true;
            } else {
                response.setStatus(401);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
